const express = require('express');
const { Op } = require('sequelize');
const { Article } = require('../../models');
const router = express.Router();
const { articleFilterBody } = require('../../utils/filter-req');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');
const getArticle = async (req) => {
  const { id } = req.params;
  const article = await Article.findByPk(id);
  if (!article) {
    throw new NotFound(`ID：${id}文章不存在`);
  }
  return article;
};
router.get('/', async (req, res) => {
  try {
    let { title, currentPage, pageSize, deleted } = req.query;
    pageSize = Math.abs(Number(pageSize || 10));
    currentPage = Math.abs(Number(currentPage || 1));
    const condition = {
      // order: [['id', 'DESC']],
      where: {},
      limit: pageSize,
      offset: (currentPage - 1) * pageSize,
    };

    /**查询软删除文章 */
    if (deleted === 'true') {
      condition.paranoid = false;
      condition.where.deletedAt = {
        [Op.not]: null,
      };
    }
    if (title) {
      condition.where.title = {
        [Op.like]: `%${title}%`,
      };
    }

    const { count, rows } = await Article.findAndCountAll(condition);

    const data = {
      data: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    success({
      res,
      data,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const article = await getArticle(req);
    success({ res, data: article });
  } catch (error) {
    failure({ res, error });
  }
});
router.post('/', async (req, res) => {
  try {
    const body = articleFilterBody(req.body);
    const article = await Article.create(body);
    //200状态么和201不同， 201表示请求成功并且创建新的资源 更专业
    success({ res, code: 201, message: '创建成功' });
  } catch (error) {
    failure({ res, error, message: '创建文章失败' });
  }
});
/**
 * 从回收站恢复
 * POST /admin/articles/restore
 */
router.post('/restore', async function (req, res) {
  try {
    const { ids } = req.body;

    await Article.restore({ where: { id: ids } });
    success({ res, message: '已恢复成功。' });
  } catch (error) {
    failure({ res, error });
  }
});

/**
 * 删除到回收站
 * POST /admin/articles/delete
 */
router.post('/delete', async function (req, res) {
  try {
    const { ids } = req.body;

    await Article.destroy({ where: { id: ids } });
    success({ res, message: '已删除到回收站。' });
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 彻底删除
 * POST /admin/articles/force_delete
 */
router.post('/force_delete', async function (req, res) {
  try {
    const { ids } = req.body;

    await Article.destroy({
      where: { id: ids },
      force: true, //彻底删除
    });
    success({ res, message: '已彻底删除。' });
  } catch (error) {
    failure({ res, error });
  }
});

// /**彻底删除 */
// router.delete('/:id', async (req, res) => {
//     try {
//         const article = await getArticle(req)
//         //删除
//         await article.destroy()
//         success({ res, message: '删除成功' })

//     } catch (error) {
//         failure({ res, error, message: '删除文章失败' })
//     }
// })

router.put('/:id', async (req, res) => {
  try {
    const article = await getArticle(req);
    const body = articleFilterBody(req.body);
    await article.update(body);
    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
